package net.aiion.weave.impl.ui.xhtml;

import java.util.Collection;
import java.util.Map;

import net.aiion.weave.spi.naming.annotations.Named;
import net.aiion.weave.spi.naming.annotations.NotScoped;
import net.aiion.weave.spi.painters.PaintBrush;
import net.aiion.weave.spi.painters.PaintContext;
import net.aiion.weave.spi.painters.annotations.Paints;
import net.aiion.weave.spi.painters.stream.xhtml.XhtmlPaintBrush;

@NotScoped
@Named
public class StyleSheetPainterHtml
{
    public StyleSheetPainterHtml() {
    }

    @Paints(StyleSheet.class)
    public PaintBrush paintStyleSheet(final PaintContext aPainterContext) {
        final XhtmlPaintBrush htmlDevice = aPainterContext.getPaintBrush(XhtmlPaintBrush.class);
        final StyleSheet styleSheet = aPainterContext.getComponent(StyleSheet.class);

        final Collection<StyleClass> styleClasses = styleSheet.getClasses();
        if (styleClasses.isEmpty()) {
            return aPainterContext.forwardPaint();
        }

        htmlDevice.startElement("style");
        htmlDevice.addAttribute("type", "text/css");
        for (StyleClass styleClass : styleClasses) {
            htmlDevice.writeCharacters(styleClass.getName() + " {");
            for (Map.Entry<String, String> styleRule : styleClass.getRules().entrySet()) {
                htmlDevice.writeCharacters("  " + styleRule.getKey() + ": " + styleRule.getValue());
            }
            htmlDevice.writeCharacters("}");
        }
        htmlDevice.endElement();

        return htmlDevice;
    }
}
